<template>
    <div class="member-page">
      <!-- 按钮集合 -->
      <div class="page-btns">
        <div class="search-btn">
          <el-input v-model="input_username" class="btn-input" placeholder="请输入会员用户名" />
          <el-button :icon="Search" type="primary" @click="search_btn">搜索</el-button>
        </div>
        <div class="other-btn">
          <el-button type="primary" :icon="Plus" @click="saveMember_btn" disabled>添加平台会员</el-button>
          <el-button type="success" :icon="Delete" :disabled="deleteAllBtn" @click="deleteMoreMembers_btn">批量删除平台会员</el-button>
        </div>
      </div>
      <!-- 用户信息表部分 -->
      <el-table :data="memberList" border style="width: 100%" @select-all="tableSelectChange" @select="tableSelectChange">
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="password" label="用户密码" />
        <el-table-column prop="nickname" label="用户昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机" />
        <el-table-column prop="avatar" label="头像" align="center">
          <template #="{row,$index}">
            <img :src="row.avatar" alt="用户头像" title="用户头像" style="width: 60px; height:60px;">
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" align="center"/>
        <el-table-column label="操作" align="center" width="130">
          <template #="{row,$index}">
            <el-button :icon="Edit" type="primary" title="编辑平台会员" @click="updateMember_btn(row)"></el-button>
            <el-popconfirm title="确定要删除该平台会员吗?" @confirm="deleteMember_btn(row)">
              <template #reference>
                <el-button :icon="Delete" type="info" title="删除平台会员"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器部分 -->
      <el-pagination background layout="prev, pager, next, total, sizes, ->, jumper" :total="memberTotal" :page-sizes="[3,5,10,20,30,50]" :default-page-size="pagination_size" @change="pagination_change" class="page-pagination"/>
      <!-- drawer_dialog抽屉部分 -->
      <el-drawer ref="drawerRef" v-model="drawer_dialog" v-if="drawer_dialog" :title="drawerState === 0 ? '添加平台会员' : '更新平台会员信息'" :before-close="handleClose" direction="rtl" class="drawerDialog">
        <div class="drawerDialog_content">
          <el-form :model="memberInfo" :rules="rules" ref="userInfoForms">
            <el-form-item label="用户名" prop="username" required label-width="80px">
              <el-input v-model="memberInfo.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户密码" prop="password" required label-width="80px">
              <el-input v-model="memberInfo.password" autocomplete="off" show-password />
            </el-form-item>
            <el-form-item label="用户昵称" label-width="80px">
              <el-input v-model="memberInfo.nickname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户邮箱" label-width="80px">
              <el-input v-model="memberInfo.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户手机" label-width="80px">
              <el-input v-model="memberInfo.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户头像" label-width="80px">
              <el-upload class="avatar-uploader" :action="uploadServer" name="multipartFile" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess" :show-file-list="false" :limit="1">
                <img v-if="memberInfo.avatar" :src="memberInfo.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
          <div class="drawerDialog_btns">
            <el-button @click="cancel_btn">取消</el-button>
            <el-button type="primary" :loading="isLoading" @click="updateOrSaveUser_btn">提交</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from "vue";
//引入ElementPlus组件
import { ElTable, ElTableColumn, ElButton, ElPagination, ElInput, ElMessage, ElDrawer, ElForm, ElFormItem, ElIcon, ElUpload, ElPopconfirm, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue';
//引入请求函数
import { reqMemberList, reqSaveMember, reqUpdateMember, reqDeleteMember, reqDeleteMembers, reqMemberListByLikeUsername } from "@/api/member/index";

//平台会员数据列表
let memberList = ref([]);
//平台会员数据总条数
let memberTotal = ref(0);
//批量删除按钮是否禁用效果
let deleteAllBtn = ref(true);
//搜索框输入的用户名信息
let input_username = ref("");
//分页器相关数据
let pagination_page = ref(0);
let pagination_size = ref(3);

//drawer_dialog抽屉部分相关数据
let drawer_dialog = ref(false);
let drawerState = ref(0);  //0-添加平台会员用户 1-修改平台会员用户
let isLoading = ref(false);  //提交按钮的loading显示
//表单收集平台会员用户信息
const memberInfo = reactive({
  id:0,
  username:"",
  password:"",
  nickname:"",
  email:"",
  phone:"",
  avatar:"",
  updateTime:"",
  createTime:""
})
//将要批量删除的平台会员用户id数组
let willDelMemberIdList = ref<number[]>([]);
//文件上传的服务器地址
const uploadServer = "http://47.120.78.25:8090/uploadByBlob";
//表单校验
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === '' || value.length < 4) {
    callback(new Error('请输入合法的用户名'))
  } else {
    callback();
  }
}
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 4){
    callback(new Error('密码长度不能少于四位'));
  } else {
    callback();
  }
}
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
})
//文件上传前的回调
const handleBeforeUpload = (file:any) => {
  if(!(file.type === 'image/jpeg' || file.type === 'image/png')){
    ElMessage({type:"info",message:"请选择jpg/png类型的图片文件!"});
    return false;
  }
  if((file.size)/1024/1024 > 4){
    ElMessage({type:"info",message:"请选择小于4M的图片文件"});
    return false;
  }
  return true;
}
//头像上传成功的回调
const handleUploadSuccess = (response:any, uploadFile:any) => {
  memberInfo.avatar = response.data[0];
  console.log('文件上传api',response);
}

//编辑会员用户信息按钮
const updateMember_btn = (member:any) => {
  //打开drawer_dialog显示
  drawer_dialog.value = true;
  //修改drawerState状态
  drawerState.value = 1;
  //更新表单数据
  memberInfo.id = member.id;
  memberInfo.username = member.username;
  memberInfo.password = atob(member.password);  //base64--->数字
  memberInfo.nickname = member.nickname;
  memberInfo.email = member.email;
  memberInfo.phone = member.phone;
  memberInfo.avatar = member.avatar;
  memberInfo.createTime = member.createTime;
  memberInfo.updateTime = member.updateTime;
}
//删除平台会员按钮
const deleteMember_btn = async (member:any) => {
  let res = await reqDeleteMember(member.id);
  if(res.code === 200){
    ElMessage({type:"success",message:"平台会员删除成功!"});
    //更新平台会员列表信息
    getMemberList(1,3);
  }
  console.log("删除平台会员api",res);
}
//批量删除平台会员按钮
const deleteMoreMembers_btn = () => {
  //弹出messageBox提示
  ElMessageBox.confirm('确定要删除这些平台会员用户吗?','提示',{confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}).then(async () => {
      //发送请求
      let res = await reqDeleteMembers(willDelMemberIdList.value);
      if(res.code === 200) {
        //删除成功
        //提示信息
        ElMessage({type:"success",message:"批量删除平台会员成功!"});
        //更新数据列表
        getMemberList(1,3);
      } else {
        //删除失败
        ElMessage({type:"error",message:res.msg});
      }
      console.log('批量删除平台会员用户api',res);
    }).catch(() => {
      ElMessage({type: 'info',message: '取消删除!'})
  })
}
//用户信息表的ckeckBox的select事件
const tableSelectChange = (memberList:any) => {
  //控制批量删除按钮是否禁用
  if(memberList.length > 0) {
    deleteAllBtn.value = false;
  } else {
    deleteAllBtn.value = true;
  }
  //分离出用户id数组
  let memberIdList = memberList.map(item => item.id);
  willDelMemberIdList.value = memberIdList;
}
//模糊搜索平台会员用户名按钮事件
const search_btn = async () => {
  let username = input_username.value;
  if(username.trim() === '')return;
  //发送请求
  let res = await reqMemberListByLikeUsername(input_username.value);
  if(res.code === 200 && res.data.rows.length > 0) {
    let responseData = res.data.rows;
    //处理用户密码 --> 123456 -> base64编码
    responseData.forEach(item => {
      item.password = btoa(item.password.toString());
    });
    memberList.value = responseData;
    memberTotal.value = res.data.total;
    ElMessage({type:"success",message:"数据获取成功!"});
  } else if(res.code === 200 && res.data.rows.length === 0){
    ElMessage({type:"info",message:"未查询到数据!"});
  } else {
    ElMessage({type:"error",message:"请求错误!"});
  }
  console.log('根据平台会员用户名模糊搜索平台会员信息api',res);
}
//drawer_dialog关闭前回调
const handleClose = () => {
  //关闭drawer抽屉
  drawer_dialog.value = false;
  //清空memberInfo数据
  memberInfo.id = 0;
  memberInfo.username = "";
  memberInfo.password = "";
  memberInfo.nickname = "";
  memberInfo.email = "";
  memberInfo.phone = "";
  memberInfo.avatar = "";
  memberInfo.createTime = "";
  memberInfo.updateTime = "";
}
//drawer_dialog取消按钮
const cancel_btn = () => {
  handleClose();
}
//drawer_dialog提交按钮
const updateOrSaveUser_btn = async () => {
  //显示loading状态
  isLoading.value = true;
  //方式请求
  if(drawerState.value === 0) {
    //添加平台会员用户
    let res = await reqSaveMember(memberInfo);
    console.log('添加平台会员用户api',res);
    //关闭loading状态
    isLoading.value = false;
  }
  if(drawerState.value === 1) {
    //修改平台会员用户信息
    let res = await reqUpdateMember(memberInfo);
    console.log("修改平台会员用户信息api",res);
    //关闭loading状态
    isLoading.value = false;
  }
  //关闭drawer_dialog
  handleClose();
  //重新请求数据
  getMemberList(1,3);
}

//添加平台会员按钮
const saveMember_btn = () => {
  //修改drawerState状态
  drawerState.value = 0;
  //打开drawer抽屉
  drawer_dialog.value = true;
}

//获取平台会员数据列表(分页获取)
const getMemberList = async (page:number, pageSize:number) => {
  let res = await reqMemberList(page, pageSize);
  if(res.code === 200){
    //保存数据列表
    let responseData = res.data.rows;
    //处理用户密码 --> 123456 -> base64编码
    responseData.forEach(item => {
      item.password = btoa(item.password.toString());
    });
    memberList.value = responseData;
    memberTotal.value = res.data.total;
    //信息提示
    ElMessage({type:"success",message:"平台会员数据获取成功!"});
  }
  console.log("分页获取平台会员数据列表api",res);
}

//分页器的change事件
const pagination_change = (currentPage:number, pageSize:number) => {
  getMemberList(currentPage, pageSize);
}

//vue生命周期
onMounted(() => {
  getMemberList(1,3);
})
</script>

<style lang='scss'>
.member-page{
  width: 100%;

  .page-btns{
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .search-btn{
      display: flex;

      .btn-input{
        margin-right: 20px;
      }
    }
    .search-btn:nth-child(1){
      width: 350px;
    }
  }
  .page-pagination{
    margin: 40px 0;
  }

  // 头像上传部分样式
  .drawerDialog {
    .drawerDialog_content{
      .avatar-uploader{
        .avatar {
          width: 78px;
          height: 78px;
          display: block;
        } 
        .el-upload{
          border: 1px dashed var(--el-border-color);
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          transition: var(--el-transition-duration-fast);

          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 78px;
            height: 78px;
            text-align: center;
          }
        }
        .el-upload:hover {
          border-color: var(--el-color-primary);
        }
      }
    }
  }
}
</style>